package com.jingdianjichi.wx.handler;

import com.jingdianjichi.wx.ai.AnswerCache;
import com.jingdianjichi.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j

public class ReceiveTextMsgHandler implements  WxChatMsgHandler{
    @Resource
    RedisUtil redisUtil;
    @Resource
    private AnswerCache answerCache;


    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    @Override
    public String dealMsg(Map<String,String> map) {
        log.info("触发用户验证码事件");
        String toUserName=map.get("FromUserName");
        String fromUserName=map.get("ToUserName");

        Random random = new Random();
        int code = random.nextInt(9000) + 1000;
        String subscribeEvent="您的验证码为"+code+"，验证码五分钟内有效!";
        //将验证码存入redis，设置五分钟有效期，同时验证码为键，用户opid为值
        redisUtil.setNx(Integer.toString(code), toUserName,300L, TimeUnit.SECONDS);
//        stringRedisTemplate.opsForValue().setIfAbsent(toUserName, Integer.toString(code),300, TimeUnit.SECONDS);
        return subscribeEvent;
    }
    private String xml(String to, String from, String text){
        long now = System.currentTimeMillis() / 1000;
        return "<xml>\n" +
                "  <ToUserName><![CDATA[" + to + "]]></ToUserName>\n" +
                "  <FromUserName><![CDATA[" + from + "]]></FromUserName>\n" +
                "  <CreateTime>" + now + "</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA[" + (text==null?"":text) + "]]></Content>\n" +
                "</xml>";
    }
}
